import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controller.dart';

class ServerCommandsPage extends GetView<ServerCommandsController> {
  const ServerCommandsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
        title: Obx(() => Text(controller.server.value?.name ?? '快捷命令')),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => controller.addCustomCommand(),
            tooltip: '添加自定义命令',
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 系统命令
            _buildSectionTitle('系统命令', Icons.terminal, Colors.blue),
            const SizedBox(height: 12),
            _buildCommandGrid(controller.commands),
            
            // 自定义命令
            Obx(() {
              if (controller.customCommands.isEmpty) {
                return const SizedBox.shrink();
              }
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 24),
                  _buildSectionTitle('自定义命令', Icons.star, Colors.amber),
                  const SizedBox(height: 12),
                  _buildCommandGrid(controller.customCommands, isCustom: true),
                ],
              );
            }),
            
            // 提示卡片
            const SizedBox(height: 24),
            _buildTipCard(),
          ],
        ),
      ),
    );
  }

  /// 构建分组标题
  Widget _buildSectionTitle(String title, IconData icon, Color color) {
    return Row(
      children: [
        Icon(icon, size: 20, color: color),
        const SizedBox(width: 8),
        Text(
          title,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: color.withAlpha(230),
          ),
        ),
      ],
    );
  }

  /// 构建命令网格
  Widget _buildCommandGrid(List<QuickCommand> commands, {bool isCustom = false}) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        childAspectRatio: 1.3,
      ),
      itemCount: commands.length,
      itemBuilder: (context, index) {
        return _buildCommandCard(commands[index], isCustom: isCustom);
      },
    );
  }

  /// 构建命令卡片
  Widget _buildCommandCard(QuickCommand cmd, {bool isCustom = false}) {
    return Obx(() {
      final isExecuting = controller.isExecuting.value && 
                         controller.selectedCommandId.value == cmd.id;

      return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: InkWell(
          onTap: isExecuting ? null : () => controller.executeCommand(cmd),
          onLongPress: isCustom ? () => _showCustomCommandMenu(cmd) : null,
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              gradient: LinearGradient(
                colors: [
                  cmd.color.withAlpha(30),
                  cmd.color.withAlpha(10),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      cmd.icon,
                      size: 24,
                      color: cmd.color.withAlpha(200),
                    ),
                    const Spacer(),
                    if (isExecuting)
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(cmd.color),
                        ),
                      )
                    else if (isCustom)
                      Icon(Icons.more_vert, size: 16, color: Colors.grey.shade600),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  cmd.name,
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  cmd.description,
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.grey.shade600,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        ),
      );
    });
  }

  /// 显示自定义命令菜单
  void _showCustomCommandMenu(QuickCommand cmd) {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 12),
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 16),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Row(
                children: [
                  Icon(cmd.icon, size: 24, color: cmd.color),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          cmd.name,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          cmd.command,
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey.shade600,
                            fontFamily: 'monospace',
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const Divider(height: 24),
            ListTile(
              leading: const Icon(Icons.play_arrow, size: 20),
              title: const Text('执行命令', style: TextStyle(fontSize: 13)),
              onTap: () {
                Get.back();
                controller.executeCommand(cmd);
              },
              dense: true,
            ),
            ListTile(
              leading: const Icon(Icons.delete_outline, size: 20, color: Colors.red),
              title: const Text('删除命令', style: TextStyle(fontSize: 13, color: Colors.red)),
              onTap: () {
                Get.back();
                controller.deleteCustomCommand(cmd);
              },
              dense: true,
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }

  /// 构建提示卡片
  Widget _buildTipCard() {
    return Card(
      color: Colors.blue.shade50,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          children: [
            Icon(Icons.lightbulb_outline, color: Colors.blue.shade700, size: 20),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '使用提示',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue.shade900,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '• 点击命令卡片快速执行\n• 长按自定义命令可删除\n• 点击右上角 + 添加常用命令',
                    style: TextStyle(fontSize: 10, color: Colors.blue.shade800),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

